package com.mxy.myapplication.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

/**
 * 自定义圆角矩形ImageView
 */

public class RoundedCornersImageView extends android.support.v7.widget.AppCompatImageView {


    private Paint paint;

    public RoundedCornersImageView(Context context) {
        this(context, null);
    }

    public RoundedCornersImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundedCornersImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        paint = new Paint();
    }

    /**
     * 绘制圆角矩形图片
     */
    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (null != drawable) {
            Bitmap bitmap = Util.drawableToBitmap(drawable);
            Bitmap b = Util.makeRoundCorner(bitmap, 30);
            final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
            final Rect rectDest = new Rect(0, 0, getWidth(), getHeight());
            paint.reset();
            canvas.drawBitmap(b, rectSrc, rectDest, paint);
        } else {
            super.onDraw(canvas);
        }
    }
}